// 任务管理API接口
import type { Task, GetTasksParams, TaskStats } from '../types/task';
import { http, getAPI_BASE_URL_SYNC } from '../lib/http-client';
import { shouldUseMockServer } from '../config/app.config';
import { taskData } from '../data/taskData';

// 任务API基础路径
const TASK_API_BASE = `${getAPI_BASE_URL_SYNC()}/tasks`;

// API响应接口
export interface ApiResponse<T> {
  data: T;
  total: number;
  success: boolean;
  message?: string;
}

// 后端API响应格式（根据实际后端API调整）
interface BackendApiResponse<T> {
  code: number;
  message: string;
  data: T;
  total?: number;
  success?: boolean;
}

// 任务列表响应格式
interface TaskListResponse {
  tasks: Task[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

// 任务模拟API实现
const mockTaskApi = {
  async getTasks(params: GetTasksParams = {}): Promise<ApiResponse<Task[]>> {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const { page = 1, pageSize = 10, search, type, project, status, priority, assignee } = params;
    
    // 过滤数据
    let filteredData = [...taskData];
    
    if (search) {
      filteredData = filteredData.filter(task => 
        task.title.toLowerCase().includes(search.toLowerCase()) ||
        task.code.toLowerCase().includes(search.toLowerCase()) ||
        task.description.toLowerCase().includes(search.toLowerCase())
      );
    }
    
    if (type) {
      filteredData = filteredData.filter(task => task.type === type);
    }
    
    if (project) {
      filteredData = filteredData.filter(task => task.project === project);
    }
    
    if (status) {
      filteredData = filteredData.filter(task => task.status === status);
    }
    
    if (priority) {
      filteredData = filteredData.filter(task => task.priority === priority);
    }
    
    if (assignee) {
      filteredData = filteredData.filter(task => task.assignee === assignee);
    }
    
    // 分页
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedData = filteredData.slice(startIndex, endIndex);
    
    return {
      data: paginatedData,
      total: filteredData.length,
      success: true,
      message: '获取任务列表成功'
    };
  },

  async createTask(taskData: Partial<Task>): Promise<ApiResponse<Task>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const newTask: Task = {
      id: Date.now(),
      code: taskData.code || `TASK-${Date.now().toString().slice(-3)}`,
      title: taskData.title || '',
      description: taskData.description || '',
      type: taskData.type || '功能开发',
      project: taskData.project || 'KZ-DevOps平台',
      status: taskData.status || '待处理',
      priority: taskData.priority || '中',
      assignee: taskData.assignee || '',
      reporter: taskData.reporter || '',
      progress: taskData.progress || 0,
      estimatedHours: taskData.estimatedHours || 0,
      actualHours: taskData.actualHours || 0,
      deadline: taskData.deadline || new Date().toISOString().split('T')[0],
      createdAt: new Date().toISOString().split('T')[0],
      updatedAt: new Date().toISOString().split('T')[0],
      tags: taskData.tags || [],
      attachments: taskData.attachments || []
    };
    
    taskData.push(newTask);
    
    return {
      data: newTask,
      total: 1,
      success: true,
      message: '任务创建成功'
    };
  },

  async updateTask(taskId: number, taskData: Partial<Task>): Promise<ApiResponse<Task>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const index = taskData.findIndex(task => task.id === taskId);
    if (index === -1) {
      throw new Error('任务不存在');
    }
    
    taskData[index] = { 
      ...taskData[index], 
      ...taskData, 
      updatedAt: new Date().toISOString().split('T')[0] 
    };
    
    return {
      data: taskData[index],
      total: 1,
      success: true,
      message: '任务信息更新成功'
    };
  },

  async deleteTask(taskId: number): Promise<ApiResponse<boolean>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const index = taskData.findIndex(task => task.id === taskId);
    if (index === -1) {
      throw new Error('任务不存在');
    }
    
    taskData.splice(index, 1);
    
    return {
      data: true,
      total: 1,
      success: true,
      message: '任务删除成功'
    };
  },

  async getTaskStats(): Promise<ApiResponse<TaskStats>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const today = new Date().toISOString().split('T')[0];
    
    const stats: TaskStats = {
      total: taskData.length,
      inProgress: taskData.filter(task => task.status === '进行中').length,
      completed: taskData.filter(task => task.status === '已完成').length,
      overdue: taskData.filter(task => task.deadline < today && task.status !== '已完成').length,
      highPriority: taskData.filter(task => task.priority === '高' || task.priority === '紧急').length
    };
    
    return {
      data: stats,
      total: 1,
      success: true,
      message: '获取任务统计成功'
    };
  }
};

export const taskApi = {
  // 获取任务列表（支持分页、搜索、筛选）
  async getTasks(params: GetTasksParams = {}): Promise<ApiResponse<Task[]>> {
    if (shouldUseMockServer()) {
      return mockTaskApi.getTasks(params);
    }
    try {
      const { page = 1, pageSize = 10, search, type, project, status, priority, assignee } = params;
      
      // 构建查询参数
      const queryParams = new URLSearchParams({
        page: page.toString(),
        pageSize: pageSize.toString()
      });
      
      if (search) queryParams.append('search', search);
      if (type) queryParams.append('type', type);
      if (project) queryParams.append('project', project);
      if (status) queryParams.append('status', status);
      if (priority) queryParams.append('priority', priority);
      if (assignee) queryParams.append('assignee', assignee);
      
      const url = `${TASK_API_BASE}?${queryParams.toString()}`;
      
      // 发送GET请求
      const response = await http.get<BackendApiResponse<TaskListResponse>>(url);
      
      // 根据后端API响应格式调整
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        // 直接返回后端数据，不需要再次解包
        const taskList = backendData.data as TaskListResponse;
        return {
          data: taskList.tasks || [],
          total: taskList.total || 0,
          success: true,
          message: backendData.message || '获取任务列表成功'
        };
      } else {
        throw new Error(backendData.message || '获取任务列表失败');
      }
    } catch (error) {
      console.error('获取任务列表失败:', error);
      return {
        data: [],
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '获取任务列表失败'
      };
    }
  },

  // 创建任务
  async createTask(taskData: Partial<Task>): Promise<ApiResponse<Task>> {
    if (shouldUseMockServer()) {
      return mockTaskApi.createTask(taskData);
    }
    try {
      const response = await http.post<BackendApiResponse<Task>>(TASK_API_BASE, taskData);
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '任务创建成功'
        };
      } else {
        throw new Error(backendData.message || '任务创建失败');
      }
    } catch (error) {
      console.error('任务创建失败:', error);
      return {
        data: {} as Task,
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '任务创建失败'
      };
    }
  },

  // 更新任务
  async updateTask(taskId: number, taskData: Partial<Task>): Promise<ApiResponse<Task>> {
    if (shouldUseMockServer()) {
      return mockTaskApi.updateTask(taskId, taskData);
    }
    try {
      const url = `${TASK_API_BASE}/${taskId}`;
      const response = await http.put<BackendApiResponse<Task>>(url, taskData);
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '任务信息更新成功'
        };
      } else {
        throw new Error(backendData.message || '任务信息更新失败');
      }
    } catch (error) {
      console.error('任务信息更新失败:', error);
      return {
        data: {} as Task,
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '任务信息更新失败'
      };
    }
  },

  // 删除任务
  async deleteTask(taskId: number): Promise<ApiResponse<boolean>> {
    if (shouldUseMockServer()) {
      return mockTaskApi.deleteTask(taskId);
    }
    try {
      const url = `${TASK_API_BASE}/${taskId}`;
      const response = await http.delete<BackendApiResponse<boolean>>(url);
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: true,
          total: 1,
          success: true,
          message: backendData.message || '任务删除成功'
        };
      } else {
        throw new Error(backendData.message || '任务删除失败');
      }
    } catch (error) {
      console.error('任务删除失败:', error);
      return {
        data: false,
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '任务删除失败'
      };
    }
  },

  // 获取任务统计
  async getTaskStats(): Promise<ApiResponse<TaskStats>> {
    if (shouldUseMockServer()) {
      return mockTaskApi.getTaskStats();
    }
    try {
      const url = `${TASK_API_BASE}/stats`;
      const response = await http.get<BackendApiResponse<TaskStats>>(url);
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '获取任务统计成功'
        };
      } else {
        throw new Error(backendData.message || '获取任务统计失败');
      }
    } catch (error) {
      console.error('获取任务统计失败:', error);
      return {
        data: {} as TaskStats,
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '获取任务统计失败'
      };
    }
  }
};